package com.visitorspecials.tankbattle.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Player
{
	private Tank t;
	private Socket clientConnection;
	private TankBattleServer server;

	private Thread clientRecieveThread;
	private Thread clientSendThread;

	private boolean running = true;

	public Player(TankBattleServer svr, Socket sock)
	{
		this.clientConnection = sock;
		this.server = svr;
		t = new Tank(new Vector2(0, 0), svr.getActors());
		svr.getActors().add(t);

		try
		{
			ClientRecieveThread();
			ClientSendThread();
		}
		catch (Exception exc)
		{
		}
	}

	public void terminate()
	{
		running = false;
	}

	private void ClientRecieveThread() throws IOException
	{
		final Scanner s = new Scanner(clientConnection.getInputStream());

		clientRecieveThread = new Thread(new Runnable() {
			@Override
			public void run()
			{
				while (running)
				{
					try
					{
						while (running && s.hasNext() == false)
							running = clientConnection.isConnected();

						if (!running)
							break;

						String line = s.nextLine();

						String[] parts = line.split(":");

						if (parts[0].equals("A"))
						{
							float x = HelperFuncs.S2F(parts[1]);
							float y = HelperFuncs.S2F(parts[2]);

							Vector2 speed = new Vector2(x, y);

							t.setSpeed(speed);
							t.setHeading(speed.getAngle());
						}
						else if (parts[0].equals("T"))
						{
							float x = HelperFuncs.S2F(parts[1]);
							float y = HelperFuncs.S2F(parts[2]);

							t.fireShot(new Vector2(x, y));
						}
						else if (parts[0].equals("Q"))
						{
							t.removeSelfFromList();
							clientConnection.close();
							terminate();
						}

					}
					catch (Exception exc)
					{
					}
				}
			}
		});

		this.clientRecieveThread.start();
	}

	private void ClientSendThread() throws IOException
	{
		final PrintStream ps = new PrintStream(
				this.clientConnection.getOutputStream());

		clientSendThread = new Thread(new Runnable() {
			@Override
			public void run()
			{
				while (running)
				{
					try
					{
						String line = "";
						
						for (Actor a : server.getActors())
							line += a.toString();

						ps.println(line);

						try
						{
							Thread.sleep(50);
						}
						catch (Exception exc)
						{
						}
					}
					catch (Exception exc)
					{
					}
				}
			}
		});

		clientSendThread.start();
	}
}
